<?php

/**
 * This is the model class for table "post".
 *
 * The followings are the available columns in table 'post':
 * @property integer $id
 * @property string $title
 * @property string $sapo
 * @property string $content
 * @property string $sapo
 * @property string $meta_title
 * @property string $meta_keyword
 * @property string $meta_description
 * @property integer $hot
 * @property integer $status
 * @property integer $category_id
 * @property datetime $create_time
 *
 * The followings are the available model relations:
 * @property Category $category
 */
class Post extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Post the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'post';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, sapo, content', 'required'),
            array('hot,status, category_id', 'numerical', 'integerOnly' => true),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, title,main_image,content, hot, status, category_id', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'category' => array(self::BELONGS_TO, 'PostCategory', 'category_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'title' => 'Tiêu đề',
            'main_image' => 'Ảnh đại diện',
            'sapo' => 'Miêu tả ngắn',
            'content' => 'Nội dung',
            'hot' => 'Nổi bật',
            'status' => 'Trạng thái',
            'category_id' => 'Danh mục',
            'meta_title' => 'Thẻ tiêu đề',
            'meta_keyword' => 'Từ khóa',
            'meta_description' => 'Thẻ miêu tả',
            'category' => 'Danh mục'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search($category_code_identifier = NULL) {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $criteria->alias = 'post';        
        $criteria->compare('post.title', $this->title, true);                
        $criteria->compare('post.status', $this->status);
                
        $criteria->join = "INNER JOIN post_category as post_category on post_category.id = post.category_id";
        $criteria->addCondition("post_category.code_identifier = '".$category_code_identifier."'");
        return new CActiveDataProvider($this, array( 
                    'criteria' => $criteria,
                    
                ));
    }

    /**
     * 
     * @param string $categoryName
     * 
     */
    public function getPostsCategory($categoryName) {
        $categoryId = Category::model()->find('name=:name AND type=post', array(':name' => $categoryName));
        if ($categoryId == NULL) {
            $posts = Post::model()->find('category_id = :categoryId', array(':categoryId' => $categoryId));
            return $posts;
        }else
            return FALSE;
    }
    
    public function getDetailLink() {
        if (isset($this->slug))
            return Yii::app()->createUrl($this->slug);
        else
            return Yii::app()->createUrl('post/detail?id=' . $this->id);
    }
    
    public function resizeImage($height = NULL, $width = NULL, $path = NULL, $ratio = NULL) {
        //Get old size
        list($oldWidth, $oldHeight) = getimagesize($this->main_image);
        //Get path
        if ($path == NULL)
            $newPath = $this->main_image;
        // Get new sizes
        if ($ratio) {
            $newWidth = $ratio * $oldWidth;
            $newHeight = $ratio * $oldHeight;
        } if ($height == NULL && $width != NULL) {
            $newHeight = $oldHeight * $width / $oldWidth;
            $newWidth = $width;
        } else if ($width == NULL && $height != NULL) {
            $newWidth = $oldWidth * $height / $oldHeight;
            $newHeight = $height;
        } else {
            $newWidth = $width;
            $newHeight = $height;
        }
        // Get type of image
        $info = getimagesize($this->main_image);
        $type = $info[2];
        $thumb = imagecreatetruecolor($newWidth, $newHeight);
        imagealphablending($thumb, false);
        imagesavealpha($thumb, true);
        if ($type === IMAGETYPE_JPEG)
            $source = imagecreatefromjpeg($this->main_image);
        else if ($type === IMAGETYPE_PNG)
            $source = imagecreatefrompng($this->main_image);
        else
            return FALSE;
        // Resize
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight); // Output
        if ($type === IMAGETYPE_JPEG)
            if (imagejpeg($thumb, $newPath))
                return TRUE;
            else
                return FALSE;
        else if ($type === IMAGETYPE_PNG)
            if (imagepng($thumb, $newPath))
                return TRUE;
            else
                return FALSE;
    }

}